/*
鱼类管理系统
包含不同种类的鱼、AI行为和生成逻辑
为VR钓鱼游戏设计
*/

import * as THREE from 'three';

class FishManager {
  constructor(scene) {
    this.scene = scene;
    
    // 鱼类数据库
    this.fishDatabase = this.createFishDatabase();
    
    // 活跃的鱼类
    this.activeFish = [];
    this.maxFish = 20;
    
    // 鱼群
    this.fishGroups = [];
    
    this.init();
  }
  
  init() {
    console.log('🐟 鱼类管理系统初始化');
    this.spawnInitialFish();
  }
  
  createFishDatabase() {
    return {
      // 普通鱼类
      goldfish: {
        id: 'goldfish',
        name: '金鱼',
        rarity: 'common',
        baseWeight: 0.3,
        weightVariation: 0.2,
        experience: 10,
        struggle: 1,
        speed: 1.5,
        color: 0xFFD700,
        size: 0.15,
        spawnChance: 0.4,
        value: 5
      },
      
      carp: {
        id: 'carp',
        name: '鲤鱼',
        rarity: 'common',
        baseWeight: 1.2,
        weightVariation: 0.8,
        experience: 25,
        struggle: 2,
        speed: 1.2,
        color: 0xCD853F,
        size: 0.25,
        spawnChance: 0.3,
        value: 15
      },
      
      // 稀有鱼类
      bass: {
        id: 'bass',
        name: '鲈鱼',
        rarity: 'rare',
        baseWeight: 2.5,
        weightVariation: 1.5,
        experience: 50,
        struggle: 3,
        speed: 2.0,
        color: 0x556B2F,
        size: 0.35,
        spawnChance: 0.15,
        value: 40
      },
      
      trout: {
        id: 'trout',
        name: '鳟鱼',
        rarity: 'rare',
        baseWeight: 1.8,
        weightVariation: 1.0,
        experience: 40,
        struggle: 2.5,
        speed: 2.5,
        color: 0x8FBC8F,
        size: 0.3,
        spawnChance: 0.1,
        value: 30
      },
      
      // 珍稀鱼类
      salmon: {
        id: 'salmon',
        name: '三文鱼',
        rarity: 'epic',
        baseWeight: 4.0,
        weightVariation: 2.0,
        experience: 100,
        struggle: 4,
        speed: 3.0,
        color: 0xFFA07A,
        size: 0.5,
        spawnChance: 0.04,
        value: 80
      },
      
      // 传说鱼类
      goldenCarp: {
        id: 'goldenCarp',
        name: '黄金鲤',
        rarity: 'legendary',
        baseWeight: 8.0,
        weightVariation: 3.0,
        experience: 200,
        struggle: 5,
        speed: 1.8,
        color: 0xFFD700,
        size: 0.8,
        spawnChance: 0.01,
        value: 200
      }
    };
  }
  
  // 生成初始鱼群
  spawnInitialFish() {
    for (let i = 0; i < this.maxFish; i++) {
      this.spawnRandomFish();
    }
  }
  
  // 生成随机鱼
  spawnRandomFish() {
    const fishType = this.selectRandomFishType();
    const fish = this.createFish(fishType);
    
    // 随机位置
    fish.position.set(
      (Math.random() - 0.5) * 40,
      -2 - Math.random() * 8,
      (Math.random() - 0.5) * 40
    );
    
    this.activeFish.push(fish);
    this.scene.add(fish);
  }
  
  // 在指定位置附近生成鱼
  spawnFishNearPosition(position, count = 1) {
    for (let i = 0; i < count; i++) {
      const fishType = this.selectRandomFishType();
      const fish = this.createFish(fishType);
      
      // 在指定位置附近随机分布
      fish.position.set(
        position.x + (Math.random() - 0.5) * 10,
        -1 - Math.random() * 5,
        position.z + (Math.random() - 0.5) * 10
      );
      
      this.activeFish.push(fish);
      this.scene.add(fish);
    }
  }
  
  // 选择随机鱼类
  selectRandomFishType() {
    const rand = Math.random();
    let cumulativeChance = 0;
    
    for (const [key, fishData] of Object.entries(this.fishDatabase)) {
      cumulativeChance += fishData.spawnChance;
      if (rand <= cumulativeChance) {
        return key;
      }
    }
    
    return 'goldfish'; // 默认返回金鱼
  }
  
  // 创建鱼的3D模型
  createFish(fishType) {
    const fishData = this.fishDatabase[fishType];
    
    // 鱼身体
    const bodyGeometry = new THREE.CapsuleGeometry(
      fishData.size * 0.3,
      fishData.size,
      4, 8
    );
    
    const bodyMaterial = new THREE.MeshPhongMaterial({
      color: fishData.color,
      shininess: 50,
      transparent: true,
      opacity: 0.9
    });
    
    const fishMesh = new THREE.Mesh(bodyGeometry, bodyMaterial);
    
    // 鱼尾巴
    const tailGeometry = new THREE.ConeGeometry(
      fishData.size * 0.4,
      fishData.size * 0.6,
      8
    );
    
    const tailMaterial = new THREE.MeshPhongMaterial({
      color: fishData.color,
      transparent: true,
      opacity: 0.7
    });
    
    const tail = new THREE.Mesh(tailGeometry, tailMaterial);
    tail.position.set(0, 0, fishData.size * 0.8);
    tail.rotation.x = Math.PI / 2;
    
    // 鱼鳍
    const finGeometry = new THREE.PlaneGeometry(
      fishData.size * 0.3,
      fishData.size * 0.5
    );
    
    const finMaterial = new THREE.MeshPhongMaterial({
      color: fishData.color,
      transparent: true,
      opacity: 0.6,
      side: THREE.DoubleSide
    });
    
    const leftFin = new THREE.Mesh(finGeometry, finMaterial);
    leftFin.position.set(-fishData.size * 0.3, 0, -fishData.size * 0.2);
    leftFin.rotation.z = Math.PI / 6;
    
    const rightFin = new THREE.Mesh(finGeometry, finMaterial);
    rightFin.position.set(fishData.size * 0.3, 0, -fishData.size * 0.2);
    rightFin.rotation.z = -Math.PI / 6;
    
    // 组装鱼
    const fishGroup = new THREE.Group();
    fishGroup.add(fishMesh);
    fishGroup.add(tail);
    fishGroup.add(leftFin);
    fishGroup.add(rightFin);
    
    // 添加鱼的数据
    fishGroup.userData = {
      ...fishData,
      weight: fishData.baseWeight + (Math.random() - 0.5) * fishData.weightVariation,
      speed: fishData.speed + (Math.random() - 0.5) * 0.5,
      direction: new THREE.Vector3(
        Math.random() - 0.5,
        0,
        Math.random() - 0.5
      ).normalize(),
      swimTime: Math.random() * Math.PI * 2,
      changeDirectionTime: Math.random() * 5
    };
    
    return fishGroup;
  }
  
  // 创建被钓到的鱼模型（特殊展示）
  createCaughtFishModel(fishData, position) {
    const fishMesh = this.createFish(fishData.id);
    fishMesh.position.copy(position);
    fishMesh.position.y += 1; // 提升到水面上
    
    // 添加闪光效果
    const particles = this.createCatchParticles(position);
    this.scene.add(particles);
    
    // 展示动画
    const showDuration = 3000;
    const startTime = Date.now();
    
    const animate = () => {
      const elapsed = Date.now() - startTime;
      const progress = elapsed / showDuration;
      
      if (progress < 1) {
        // 旋转展示
        fishMesh.rotation.y = progress * Math.PI * 2;
        fishMesh.position.y = position.y + 1 + Math.sin(progress * Math.PI) * 0.5;
        
        requestAnimationFrame(animate);
      } else {
        // 移除展示模型
        this.scene.remove(fishMesh);
        this.scene.remove(particles);
      }
    };
    
    this.scene.add(fishMesh);
    animate();
  }
  
  // 创建钓鱼成功的粒子效果
  createCatchParticles(position) {
    const particleCount = 50;
    const geometry = new THREE.BufferGeometry();
    const positions = [];
    const colors = [];
    
    for (let i = 0; i < particleCount; i++) {
      positions.push(
        position.x + (Math.random() - 0.5) * 2,
        position.y + Math.random() * 2,
        position.z + (Math.random() - 0.5) * 2
      );
      
      colors.push(1, 1, 0); // 金色粒子
    }
    
    geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
    geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
    
    const material = new THREE.PointsMaterial({
      size: 0.1,
      vertexColors: true,
      transparent: true,
      opacity: 0.8
    });
    
    return new THREE.Points(geometry, material);
  }
  
  // 获取随机鱼（用于钓鱼）
  getRandomFish() {
    const fishType = this.selectRandomFishType();
    const fishData = { ...this.fishDatabase[fishType] };
    
    // 随机化重量
    fishData.weight = fishData.baseWeight + 
                     (Math.random() - 0.5) * fishData.weightVariation;
    
    return fishData;
  }
  
  // 更新鱼的AI行为
  updateFishAI(deltaTime) {
    this.activeFish.forEach(fish => {
      const userData = fish.userData;
      
      // 更新游泳时间
      userData.swimTime += deltaTime;
      userData.changeDirectionTime -= deltaTime;
      
      // 游泳动画（尾巴摆动）
      const tail = fish.children[1]; // 尾巴是第二个子对象
      if (tail) {
        tail.rotation.y = Math.sin(userData.swimTime * 4) * 0.3;
      }
      
      // 鱼鳍动画
      const leftFin = fish.children[2];
      const rightFin = fish.children[3];
      if (leftFin && rightFin) {
        const finMovement = Math.sin(userData.swimTime * 3) * 0.2;
        leftFin.rotation.y = finMovement;
        rightFin.rotation.y = -finMovement;
      }
      
      // 改变游泳方向
      if (userData.changeDirectionTime <= 0) {
        userData.direction.set(
          Math.random() - 0.5,
          (Math.random() - 0.5) * 0.2,
          Math.random() - 0.5
        ).normalize();
        
        userData.changeDirectionTime = 2 + Math.random() * 3;
      }
      
      // 移动鱼
      const movement = userData.direction.clone()
                        .multiplyScalar(userData.speed * deltaTime);
      fish.position.add(movement);
      
      // 边界检查
      if (Math.abs(fish.position.x) > 25) {
        userData.direction.x *= -1;
        fish.position.x = Math.sign(fish.position.x) * 25;
      }
      
      if (Math.abs(fish.position.z) > 25) {
        userData.direction.z *= -1;
        fish.position.z = Math.sign(fish.position.z) * 25;
      }
      
      if (fish.position.y > -0.5) {
        userData.direction.y = -Math.abs(userData.direction.y);
      }
      
      if (fish.position.y < -10) {
        userData.direction.y = Math.abs(userData.direction.y);
      }
      
      // 朝向游泳方向
      fish.lookAt(
        fish.position.x + userData.direction.x,
        fish.position.y + userData.direction.y,
        fish.position.z + userData.direction.z
      );
    });
  }
  
  // 移除死亡或过期的鱼
  cleanupFish() {
    // 实现鱼的生命周期管理
    const now = Date.now();
    
    this.activeFish = this.activeFish.filter(fish => {
      // 这里可以添加鱼的生命周期逻辑
      return true; // 暂时保留所有鱼
    });
    
    // 保持最大鱼数量
    while (this.activeFish.length < this.maxFish) {
      this.spawnRandomFish();
    }
  }
  
  // 更新方法
  update(deltaTime) {
    this.updateFishAI(deltaTime);
    
    // 每30秒清理一次
    if (Math.random() < deltaTime / 30) {
      this.cleanupFish();
    }
  }
  
  // 销毁资源
  destroy() {
    this.activeFish.forEach(fish => {
      this.scene.remove(fish);
    });
    
    this.activeFish = [];
    this.fishGroups = [];
  }
}

export { FishManager }; 